// org/example/demo/SqlExecutionCache.java
package org.example.batch;

import com.intellij.openapi.project.Project;
import com.intellij.psi.xml.XmlTag;
import org.example.demo.CheckAllSqlsInFileAction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public final class SqlExecutionCache {

    private static final ConcurrentMap<String, SqlCheckResult> cache = new ConcurrentHashMap<>();

    private SqlExecutionCache() {}

    /**
     * 生成唯一 key：project + file + tag start offset
     */
    private static @NotNull String getKey(@NotNull XmlTag tag) {
        Project project = tag.getProject();
        String projectPath = project.getBasePath() != null ? project.getBasePath() : "unnamed";
        String filePath = tag.getContainingFile().getVirtualFile().getPath();
        int offset = tag.getTextOffset();
        return projectPath + "::" + filePath + "::" + offset;
    }

    public static void putResult(@NotNull XmlTag tag, @NotNull SqlCheckResult result) {
        cache.put(getKey(tag), result);
    }

    public static @Nullable SqlCheckResult getResult(@NotNull XmlTag tag) {
        return cache.get(getKey(tag));
    }

    public static void clearForProject(@NotNull Project project) {
        String projectPath = project.getBasePath() != null ? project.getBasePath() : "unnamed";
        cache.keySet().removeIf(key -> key.startsWith(projectPath + "::"));
    }
}